package com.ds.common.org.expression.person;

import java.util.List;
import java.util.Set;
import java.util.Stack;

import com.ds.common.expression.ParseException;
import com.ds.common.expression.function.Function;
import com.ds.org.Person;
import com.ds.org.Role;

/**
 * <p>
 * Title: JDSORG组织机构中间件
 * </p>
 * <p>
 * Description: 3.1.34. 判断某个人是否属于某种工作组<br>
 * Boolean IsPersonInPersonGroup(Person person, PersonGroup[] groups)<br>
 * 参数： person - 指定的人员<br>
 * groups - 指定的人员工作组<br>
 * 返回值：如果此人员属于指定的任意一个人员工作组返回True，否则返回False<br>
 * </p>
 * <p>
 * Copyright: jds Copyright (c) 2003-2008
 * </p>
 * <p>
 * Company: www.justdos.net
 * </p>
 *
 * @author lxl
 * @version 2.0
 */
public class IsPersonInPersonGroup extends Function {
    public IsPersonInPersonGroup() {
	numberOfParameters = 2;
    }

    public void run(Stack stack) throws ParseException {
	checkStack(stack); // check the stack
	Object param2 = stack.pop();
	Object param1 = stack.pop();
	stack.push(perform(param1, param2));
    }

    protected Boolean perform(Object param1, Object param2) throws ParseException {
	if (param1 == null || param2 == null) {
	    return Boolean.FALSE;
	}
	if (param1 instanceof Person && param2 instanceof Role[]) {


        Person person = (Person) param1;

        Role[] groups = (Role[]) param2;

        Set<String> dutyIdList = person.getRoleIdList();
        for (String dutyId : dutyIdList) {

            if (dutyId == null) {
                continue;
            }

            for (Role duty: groups) {
                if (dutyId.equalsIgnoreCase(duty.getRoleId())) {
                    return Boolean.TRUE;
                }
            }
        }
        return Boolean.FALSE;


	}
	throw new ParseException("Invalid parameter type in:" + this.getClass().getName() + ", param1 is " + param1.getClass().getName() + ", param2 is " + param2.getClass().getName());
    }
}
